<template>
  <div class="register-container">
    <el-form class="register-form" autoComplete="on" :model="registerForm" ref="registerForm" :rules="registerRules"
             label-position="left">
      <h3 class="title"> {{H3title}}</h3>
      <el-form-item prop="username" v-show="!isHideUserName" >
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="user"/>
        </span>
        <el-input name="username" v-model="registerForm.username" autoComplete="off" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item prop="phone">
        <span class="svg-container svg-container_login">
          <svg-icon icon-class="mobile"/>
        </span>
        <el-input name="phone" v-model="registerForm.phone" autoComplete="off" placeholder="请输入手机号"/>
      </el-form-item>
      <el-form-item prop="verificationCode" v-show="!site.adminSmsCodeLogin">
        <span class="svg-container">
          <svg-icon icon-class="email"></svg-icon>
        </span>
        <el-input name="verificationCode" v-model="registerForm.verificationCode" autoComplete="off"
                  placeholder="请输入短信验证码">
        </el-input>
        <el-button class="msg-sending" type="text" @click="sendMsg" v-show="show" :loading="msg_loading"> 获取短信验证码
        </el-button>
        <span class="msg-sended" v-show="!show">  {{count}}s后重试 </span>
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"></svg-icon>
        </span>
        <el-input name="password" v-model="registerForm.password" autoComplete="off"
                  placeholder="请输入6-16位密码">
        </el-input>
      </el-form-item>

      <el-form-item prop="rePassword">
        <span class="svg-container">
          <svg-icon icon-class="password"></svg-icon>
        </span>
        <el-input name="rePassword" v-model="registerForm.rePassword" autoComplete="off"
                  placeholder="请重复密码">
        </el-input>

      </el-form-item>

      <el-form-item>
        <el-button type="primary" style="width:100%;" :loading="loading" @click.native.prevent="handleRegister">
          确认
        </el-button>
      </el-form-item>
      <div class="tips">
        <el-button type="text" @click="gotoLogin">登录</el-button>
      </div>
    </el-form>
  </div>
</template>


<script>
  import { get } from '@/api/sys/connSysOpenApi'

  export default {
    name: 'register',
    created() {
      this.getSite()
    },
    beforeRouteEnter(to, form, next) {
      let type = 0
      if (to.path === '/auth/user/register') {
        type = 1
      }
      if (to.path === '/auth/user/resetpwd') {
        type = 2
      }
      next(vm => vm.setH3Title(type))
    },

    data() {
      const defaultSite = {
        'adminKaptcha': false,
        'adminSmsCodeLogin': false,
        'enable': true,
        'adminPwdMinLength': 6,
        'name': undefined,
        'adminSmsCodeRegister': false,
        'addr': undefined,
        'version': undefined,
        'adminPwdMaxLength': 16
      }

      const validatePhone = (rule, value, callback) => {
        if (value !== null) {
          if (value.toString().length !== 11) {
            callback(new Error('手机号码位数不正确'))
          } else if (!/1[3456789]\d{9}$/.test(value)) {
            callback(new Error('请输入有效的手机号码'))
          } else {
            callback()
          }
        } else {
          callback(new Error('请输入手机号码'))
        }
      }

      const validatePassword = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入密码'))
        }
        if (value.length < this.site.adminPwdMinLength) {
          callback(new Error('密码不能小于' + this.site.adminPwdMinLength + '位'))
        } else if (value.length > this.site.adminPwdMaxLength) {
          callback(new Error('密码不能大于' + this.site.adminPwdMaxLength + '位'))
        } else {
          callback()
        }
        // else if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/.test(value)) {
        //     callback(new Error('密码必须包含字母和数字'))
        //   }
      }

      const validateRePassword = (rule, value, callback) => {
        if (!value || value === '') {
          callback(new Error('密码不能为空'))
        } else if (value !== this.registerForm.password) {
          callback(new Error('两次密码不一致！'))
        } else {
          callback()
        }
      }
      return {
        site: Object.assign({}, defaultSite),
        registerForm: {
          phone: '',
          verificationCode: '',
          password: '',
          rePassword: ''
        },
        registerRules: {
          phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
          password: [{ required: true, validator: validatePassword }],
          rePassword: [{ required: true, validator: validateRePassword }],
          verificationCode: [{ required: true, message: '验证码不能为空' }],
          username: [{ required: true, message: '用户名不能为空' }]
        },
        show: true,
        loading: false,
        msg_loading: false,
        count: 60,
        timer: null,
        H3title: '...',
        handleType: '',
        sendMsgType: '',
        isHideUserName: false
      }
    },
    methods: {
      gotoLogin() {
        this.$router.push({ path: '/login' })
      },
      getSite() {
        get('site').then(res => {
          this.site = res.site
        }).catch((err) => {
          this.site = err.site
        })
      },
      setH3Title(type) {
        if (type === 1) {
          this.H3title = '注册'
          this.handleType = 'Register'
          this.isHideUserName = false
          this.sendMsgType = 'SendRegisterMsg'
        }
        if (type === 2) {
          this.H3title = '重置密码'
          this.handleType = 'Repwd'
          this.isHideUserName = true
          this.sendMsgType = 'SendRepwdMsg'
        }
      },
      sendMsg() {
        this.$refs.registerForm.validateField('phone', (valid) => {
          if (!valid) {
            this.msg_loading = true
            this.$store.dispatch(this.sendMsgType, this.registerForm.phone).then(() => {
              this.msg_loading = false
              this.show = false
              if (!this.timer) {
                this.show = false
                this.timer = setInterval(() => {
                  if (this.count > 0 && this.count <= 60) {
                    this.count--
                  } else {
                    this.count = 60
                    this.show = true
                    // clearInterval(this.timer)
                    // this.timer = null
                  }
                }, 1000)
              }
            }).catch(() => {
              this.msg_loading = false
            })
          }
        })
      },
      handleRegister: function() {
        this.registerRules.username[0].required = !this.isHideUserName
        this.$refs.registerForm.validate(valid => {
          if (valid) {
            this.loading = true
            this.$store.dispatch(this.handleType, this.registerForm).then(res => {
              this.loading = false
              if (res.code !== 200) {
                this.$notify({
                  title: '提示!',
                  message: res.message,
                  type: 'error',
                  duration: 2000
                })
              } else {
                let str = ''
                if (this.handleType === 'Register') {
                  str = '注册成功'
                }
                if (this.handleType === 'Repwd') {
                  str = '密码重置成功'
                }
                this.$alert('请重新登录', str, {
                  confirmButtonText: '登录',
                  callback: action => {
                    this.$router.push({ path: '/login' })
                  }
                })
              }
            }).catch(error => {
              console.log(error)
              this.loading = false
            })
            // add(this.handleType, this.registerForm).then(res => {
            //   console.log(res)
            //   if (res.code !== 200) {
            //     this.$notify({
            //       title: '提示!',
            //       message: res.message,
            //       type: 'error',
            //       duration: 2000
            //     })
            //   } else {
            //     this.$alert('请重新登录', '注册成功', {
            //       confirmButtonText: '登录',
            //       callback: action => {
            //         this.$router.push({ path: '/login' })
            //       }
            //     })
            //   }
            // })
          }
        })
        // this.$confirm('注册成功，请重新登录', '提示', {
        //   confirmButtonText: '确定',
        //   cancelButtonText: '登录',
        //   type: 'success'
        // }).then(() => {
        //   console.log('请求成功1')
        // }).catch(() => {
        //   console.log('请求成功2')
        // })
      }
    }

  }
</script>
<style rel="stylesheet/scss" lang="scss">
  $bg: #2d3a4b;
  $light_gray: #eee;

  /* reset element-ui css */
  .register-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;

        &:-webkit-autofill {
          -webkit-box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: #fff !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }

</style>
<style rel="stylesheet/scss" lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;
  .register-container {
    position: fixed;
    height: 100%;
    width: 100%;
    background-color: $bg;

    .register-form {
      position: absolute;
      left: 0;
      right: 0;
      width: 520px;
      padding: 35px 35px 15px 35px;
      margin: 120px auto;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .title {
      font-size: 26px;
      font-weight: 400;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }

    .msg-sending {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $light_gray;
      cursor: pointer;
      user-select: none;
    }

    .msg-sended {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }
  }
</style>
